package com.express.e.root.service.impl;

import com.express.e.root.bean.Delivery;
import com.express.e.root.dao.DeliveryDao;
import com.express.e.root.dao.impl.DeliveryDaoImpl;
import com.express.e.root.service.DeliveryService;

import java.util.List;
import java.util.Random;

public class DeliveryServiceImpl implements DeliveryService {
    private DeliveryDao deliveryDao = new DeliveryDaoImpl();
    @Override
    public Delivery addDelivery(Delivery delivery) {
        delivery = randomCode(delivery);
        while(deliveryDao.codeIsRepeated(Integer.valueOf(delivery.getDeliveryCode()))){
            delivery = randomCode(delivery);
        }
        Boolean addFlag = deliveryDao.addDelivery(delivery);
        if (addFlag) {
            return deliveryDao.queryByCode(Integer.valueOf(delivery.getDeliveryCode()));
        }
        return null;
    }

    @Override
    public Boolean deleteDelivery(String deliveryNum) {
        return deliveryDao.deleteDelivery(deliveryNum);
    }

    @Override
    public Boolean fetchDelivery(String deliveryNum) {
        return deliveryDao.fetchDelivery(deliveryNum);
    }

    @Override
    public List<Delivery> queryByList(int pageIndex,int pageSize) {
        return deliveryDao.queryByList(pageIndex, pageSize);
    }

    @Override
    public Delivery updateDelivery(Delivery delivery) {
        Boolean updateFlag = deliveryDao.updateDelivery(delivery);
        if (updateFlag) {
            return  deliveryDao.queryById(delivery.getDeliveryId());
        }
        return null;
    }

    @Override
    public Integer total() {
        return deliveryDao.total();
    }

    @Override
    public Delivery randomCode(Delivery delivery) {
        int code = new Random().nextInt(899999) + 100000;
        delivery.setDeliveryCode(String.valueOf(code));
        return delivery;
    }

    @Override
    public List<Delivery> queryAll() {
        return deliveryDao.queryAll();
    }

    @Override
    public Delivery queryById(Integer deliveryId) {
        return deliveryDao.queryById(deliveryId);
    }

    @Override
    public Delivery queryByCode(Integer deliveryCode) {
        return deliveryDao.queryByCode(deliveryCode);
    }


    @Override
    public Delivery queryByNum(String deliveryNum) {
        return deliveryDao.queryByNum(deliveryNum);
    }

    @Override
    public Delivery queryByName(String deliveryName) {
        return deliveryDao.queryByName(deliveryName);
    }

    @Override
    public Delivery queryByPhone(String phone) {
        return deliveryDao.queryByPhone(phone);
    }

    @Override
    public List queryListByName(String name) {
        return deliveryDao.queryListByName(name);
    }

    @Override
    public List queryListByCourier(String courierName) {
        return deliveryDao.queryListByCourier(courierName);
    }


}
